package org.shj.netty.chartper2.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable{

	//private int port;
	CountDownLatch latch;
	AsynchronousServerSocketChannel serverSocketChannel;
	
	public AsynchronousServerSocketChannel getServerSocketChannel() {
		return serverSocketChannel;
	}

	public void setServerSocketChannel(
			AsynchronousServerSocketChannel serverSocketChannel) {
		this.serverSocketChannel = serverSocketChannel;
	}

	public AsyncTimeServerHandler(int port){
		//this.port = port;
		try{
			serverSocketChannel = AsynchronousServerSocketChannel.open();
			serverSocketChannel.bind(new InetSocketAddress(port));
			System.out.println("The time server is start in port: " + port);
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public void run(){
		System.out.println("AsyncTimeServerHandler.run()");
		latch = new CountDownLatch(1); 
		System.out.println("after latch countdown");
		doAccept();
		try{
			latch.await();//线程在此阻塞
			
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	
	public void doAccept(){
		System.out.println("doAccept()");
		serverSocketChannel.accept(this, new AcceptCompletionHandler());
	}
}
